<template>
    <div class="main_content">
        <div class="left">
            <div class="top">
                <Input  v-model="deptKeyword"  placeholder="请输入组织机构名称" style="width:280px;" clearable/>
                <input type="password" autocomplete="new-password" style="display: none" />
            </div>
            <div class="scorll">
                <el-tree :data="treeList"  ref="treeBox"  node-key="id" :render-content="renderContent" :expand-on-click-node="false" :highlight-current="true" :filter-node-method="filterNode" :default-expanded-keys="[checkId]"></el-tree>
            </div>
        </div>
        <div class="left">
            <div class="top">
                <el-button @click="getEditmodal(0)" style="margin-right:10px" v-if="auth.isAddRole" type="primary" size="small" plain icon="el-icon-plus">角色</el-button>
                <Input search @on-search="search" v-model="keyword"  placeholder="请输入角色名称" style="width:200px;" clearable/>
                <input type="password" autocomplete="new-password" style="display: none" />
            </div>
            <div class="bottom">
                <ul>
                    <li v-for="(item,index) in roleList" :key="index" :class="item.id == roleId?'active':''" @click="getDetails(item)">
                        <span>{{item.name}}</span>
                        <p>
                            <span>
                                <i class="el-icon-edit-outline" @click="getEditmodal(1,item)" v-if="auth.isEditRole"></i>
                                <!-- <i class="el-icon-edit-outline" style="cursor: not-allowed" v-if="!auth.isEditRole"></i> -->
                            </span>
                            <span v-if="item.name != '超级管理员' ">
                                <i class="el-icon-delete" @click="removeRow(item)" v-if="auth.isDelRole"></i>
                                <!-- <i class="el-icon-delete" style="cursor: not-allowed" v-if="!auth.isDelRole"></i> -->
                            </span>
                        </p>
                    </li>
                </ul>
            </div>
        </div>
        <div class="right">
            <div v-if="roleList.length>0" style="height:100%">
                <div class="list">
                    <p>角色名称:
                        <span style="color:#1891ff">{{Titlename}}</span>
                    </p>
                </div>
                <el-tabs v-model="tabActiveName" @tab-click="tabChange">
                    <el-tab-pane label="后台权限" name="1">
                        <div class="tree">
                            <el-tree ref="HTtree" :data="treeData" :props="multiProps" show-checkbox node-key="ruleId" highlight-current :expand-on-click-node="false" :default-checked-keys="checkedHTList" :check-strictly="true" @check="clickHTDeal"></el-tree>
                        </div>
                        <div class="btn">
                            <el-button @click="rolesubmitAll(1)" type="primary" size="small" plain v-preventReClick="1500" v-if="auth.isSave">保存</el-button>
                        </div>
                    </el-tab-pane>
                    <el-tab-pane label="APP权限" name="2">
                        <div class="tree">
                        <el-tree ref="XCXtree" :data="treeData1" :props="multiProps" show-checkbox node-key="ruleId" highlight-current :expand-on-click-node="false" :default-checked-keys="checkedXCXList" :check-strictly="true" @check="clickCXCDeal"></el-tree>
                        </div>
                        <div class="btn">
                            <el-button @click="rolesubmitAll(2)" type="primary" size="small" plain v-preventReClick="1500" v-if="auth.isSave">保存</el-button>
                        </div>
                    </el-tab-pane>
                    <el-tab-pane label="使用账号" name="3">
                        <el-table :data="UserList" border :height="tableHeight">
                            <el-table-column prop="username" label="用户名"></el-table-column>
                            <el-table-column prop="nickname" label="姓名"></el-table-column>
                            <el-table-column prop="phone" label="电话号"></el-table-column>
                            <el-table-column prop="status" label="状态">
                                <template slot-scope="scope">
                                    <span v-if="scope.row.status == 0">禁用</span>
                                    <span v-if="scope.row.status == 1">启用</span>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-tab-pane>
                </el-tabs>
            </div>
        </div>

        <Modal v-model="deleteModal" title="删除" width="360px;" :mask-closable="false">
            <div style="margin:10px">确定要删除这条数据吗？</div>
            <div slot="footer">
                <el-button @click="cancel(2)" type="info" size="small" plain>取消</el-button>
                <el-button @click="detele" type="primary" size="small" plain v-preventReClick="1500">确定</el-button>
            </div>
        </Modal>

        <Modal v-model="Editmodal" :title="isAdd?'添加角色':'编辑角色'" :mask-closable="false">
            <div class="list">
                <span class="tip">*</span>
                <span>角色名:</span>
                <Input v-model="username" placeholder="请输入角色名" style="width: 300px" show-word-limit :maxlength="limitlength" clearable/>
            </div>
            <div class="list">
                <span>角色描述:</span>
                <Input v-model="description" type="textarea" placeholder="请输入描述" style="width: 300px" clearable/>
            </div>
            <div slot="footer">
                <el-button @click="cancel(1)" type="info" size="small" plain>取消</el-button>
                <el-button @click="submitAll" type="primary" size="small" plain v-preventReClick="1500">保存</el-button>
            </div>
        </Modal>
    </div>
</template>

<script>
import { treeSort, trans } from "@/sever/config.js";
import { bubbleSort } from "@/sever/config.js";
import { ruleTree, disTree } from "@/sever/rule.js";
import {
    getRoleList,
    getRolePageList,
    getRoleDetails,
    getRoleAdd,
    getRoleEdit,
    getRuleModuleList,
    getRoleRemove,
    getRolerUserlist,
    geRoletRuleEdit,
    getAlldeptList,
    getRoleUserDept
} from "@/api/api.js";
import {initSys} from "@/mixins/sys.js"

export default {
    mixins:[initSys],
    data() {
        return {
            pageNum: 1,
            pageSize: 100,
            isAdd: "",
            username: "",
            treeData: [],
            treeid: "",
            id: "",
            deleteModal: false,
            ids: "",
            ruleHTlist: [],
            ruleXCXlist: [],
            btnList:[],
            multiProps: {
                children: "children",
                label: "title",
            },
            checkedId: [],
            description: "",
            UserList: [],
            Username: "",
            Editmodal: false,
            treeid1: [],
            platform: "",
            roleId: "",
            tabActiveName: "1",
            tableHeight: window.innerHeight - 250,
            checkedHTList: [],
            checkedXCXList: [],
            treeData1: [],
            keyword:"",
            Titlename:"",
            deptKeyword:"",
            treeList:[],
            checkId:"",
            deptId:"",
            limitlength:16,
            auth:{
                isAddRole:false,
                isSave: false,
                isDelRole:false,
                isEditRole:false,
            }, 
        };
    },
    watch:{
        deptKeyword(val){
            this.$refs.treeBox.filter(val);
        }
    },
    methods: {
        initAuth(){
            this.auth.isAddRole = this.btnList.includes('sys/role/add')
            this.auth.isSave = this.btnList.includes('sys/role/save')
            this.auth.isDelRole = this.btnList.includes('sys/role/del')
            this.auth.isEditRole = this.btnList.includes('sys/role/edit')
        },
        renderContent (h, { root, node, data }) {
            if( data.type == 0 ) {
               return (
                    <span class="custom-tree-node">
                        <span class="sub">公</span>
                        <span class="title" on-click={ () => this.getTreeId(data,node)}>{data.label}</span>
                    </span>
                )
            }  else if (data.type == 1) {
                return (
                    <span class="custom-tree-node">
                        <span class="sub">项</span>
                        <span class="title" on-click={ () => this.getTreeId(data,node)}>{data.label}</span>
                    </span>
                )
        }
        },
        filterNode(value, data) {
            if (!value) return true;
            return data.label.indexOf(value) !== -1;
        },
        getTreeId(data){
            this.deptId = data.id;
            this.getList(3);
        },
        //获取组织机构
        getDeptList(){
            let params = {
                keyword:"",
            }
            getAlldeptList(params).then(res=>{
                if(res.code == 200) {
                    let list = res.data.list;
                    this.treeList = treeSort(trans(list));
                    this.checkId = this.treeList[0].id;
                    this.deptId = this.treeList[0].id;
                    this.$nextTick(() => {
                        // treeBox 元素的ref   value 绑定的node-key
                        this.$refs.treeBox.setCurrentKey( this.deptId);
                    });
                    this.getList(2);
               } else {
                   this.$Message.warning(res.msg);
               }
            }).catch(error=>{
                console.log(error)
            })
        },
        //后台
        clickHTDeal(currentObj, treeStatus) {
            // 用于:父子节点严格互不关联时，父节点勾选变化时通知子节点同步变化，实现单向关联。
            let selected = treeStatus.checkedKeys.indexOf(currentObj.ruleId); // -1未选中
            let count = currentObj.children || 0;
            // 选中
            if (selected !== -1) {
                // 子节点只要被选中父节点就被选中
                this.selectedParent(currentObj);
                // 统一处理子节点为相同的勾选状态
                this.uniteChildSame(currentObj, true);
            } else {
                // 未选中 处理子节点全部未选中
                if (count.length !== 0 ) {
                    this.uniteChildSame(currentObj, false);
                }
            }
        },
        // 统一处理子节点为相同的勾选状态
        uniteChildSame(list, isSelected) {
            let treeListData = list.children || [];
            let len = treeListData.length || 0;
            this.$refs.HTtree.setChecked(list.ruleId, isSelected);
            for (let i = 0; i < len; i++) {
                this.uniteChildSame(treeListData[i], isSelected);
            }
        },
        // 统一处理父节点为选中
        selectedParent(currentObj) {
            let currentNode = this.$refs.HTtree.getNode(currentObj);
            if (currentNode.parent.key !== undefined) {
                this.$refs.HTtree.setChecked(currentNode.parent, true);
                this.selectedParent(currentNode.parent);
            }
        },
        //APP
        clickCXCDeal(currentObj, treeStatus) {
            // 用于:父子节点严格互不关联时，父节点勾选变化时通知子节点同步变化，实现单向关联。
            let selected = treeStatus.checkedKeys.indexOf(currentObj.ruleId); // -1未选中
            let count = currentObj.children || 0;
            // 选中
            if (selected !== -1) {
                // 子节点只要被选中父节点就被选中
                this.selectedCXCParent(currentObj);
                // 统一处理子节点为相同的勾选状态
                this.uniteCXCChildSame(currentObj, true);
            } else {
                // 未选中 处理子节点全部未选中
                if (count.length !== 0 ) {
                    this.uniteCXCChildSame(currentObj, false);
                }
            }
        },
        // 统一处理子节点为相同的勾选状态
        uniteCXCChildSame(list, isSelected) {
            let treeListData = list.children || [];
            let len = treeListData.length || 0;
            this.$refs.XCXtree.setChecked(list.ruleId, isSelected);
            for (let i = 0; i < len; i++) {
                this.uniteCXCChildSame(treeListData[i], isSelected);
            }
        },
        // 统一处理父节点为选中
        selectedCXCParent(currentObj) {
            let currentNode = this.$refs.XCXtree.getNode(currentObj);
            if (currentNode.parent.key !== undefined) {
                this.$refs.XCXtree.setChecked(currentNode.parent, true);
                this.selectedCXCParent(currentNode.parent);
            }
        },
        //获取用户列表
        getList(type) {
            this.getRoleList(this.keyword, this.deptId,true,type);
        },
        search(){
            this.getList(1);
        },
        getDetails(item) {
            this.roleId = item.id;
            this.Titlename = item.name;
            this.tabActiveName = "1";
            this.updateHTRow(true);
        },
        tabChange(tab, evnet) {
            if (tab.name == 1) {
                this.updateHTRow(true);
            } else if (tab.name == 2) {
                this.updateXCXRow();
            } else if (tab.name == 3) {
                this.RolerUserlist(this.roleId);
            }
        },
        //角色用户
        RolerUserlist(id) {
            let params = {
                roleId: id,
            };
            getRolerUserlist(params)
                .then((res) => {
                    if (res.code == 200) {
                        this.UserList = res.data.list;
                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch((error) => {
                    console.log(error);
                });
        },
        // HT权限编辑
        updateHTRow(type) {
            this.checkedHTList = [];
            if(type){
                this.$nextTick(() => {
                    if (this.$refs.HTtree) {
                        this.$refs.HTtree.setCheckedKeys([])
                    }
                })
            }
            let params = {
                roleId: this.roleId,
                platform: 1,
            };
            getRoleDetails(params)
                .then((res) => {
                    if (res.code == 200) {
                        res.data.list.forEach(i=>{
                            this.checkedHTList.push(i.id)
                        })
                        this.checkedHTList = JSON.parse(JSON.stringify(this.checkedHTList));
                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch((error) => {
                    console.log(error);
                });
        },
        //XCX权限编辑
        updateXCXRow() {
            this.checkedXCXList = [];
            this.$refs.XCXtree.setCheckedKeys([])
            let params = {
                roleId: this.roleId,
                platform: 2,
            };
            getRoleDetails(params)
                .then((res) => {
                    if (res.code == 200) {
                        res.data.list.forEach(i=>{
                            this.checkedXCXList.push(i.id)
                        })
                        this.checkedXCXList = JSON.parse(JSON.stringify(this.checkedXCXList));
                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch((error) => {
                    console.log(error);
                });
        },
        getEditmodal(type, item) {
            this.Editmodal = true;
            if (type == 0) {
                this.isAdd = true;
                this.username = "";
                this.description = "";
            } else {
                this.isAdd = false;
                this.username = item.name;
                this.id = item.id;
                this.description = item.description ? item.description : "";
            }
        },
        rolesubmitAll(type) {
            if(type == 1) {
                this.checkedId = this.$refs.HTtree.getCheckedKeys();
            } else if(type == 2) {
                this.checkedId = this.$refs.XCXtree.getCheckedKeys();
            }
            this.treeid1 = this.checkedId;
            this.treeid = this.checkedId.join(",");
            if (this.treeid === "") {
                this.$Modal.warning({
                    title: "您有必填字段",
                    content: "权限管理不能为空 ",
                });
                return;
            }
            let params = {
                ruleIds: this.treeid1,
                roleId: this.roleId,
                platform: type,
            };
            geRoletRuleEdit(params)
                .then((res) => {
                    if (res.code == 200) {
                        this.success();
                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch((error) => {
                    console.log(error);
                });
        },
        submitAll() {
            if (this.username === "") {
                this.$Modal.warning({
                    title: "您有必填字段",
                    content: "角色名不能为空",
                });
                return;
            }
            if (this.description != "") {
                if (this.description.length > 50) {
                    this.$Modal.warning({
                        title: "提示",
                        content: "最多只能添加50字以内的描述",
                    });
                    return;
                }
            }
            if (this.isAdd) {
                let params = {
                    description: this.description,
                    name: this.username,
                    deptId:this.deptId,
                };
                getRoleAdd(params)
                    .then((res) => {
                        if (res.code == 200) {
                            this.success();
                        } else {
                            this.$Message.warning(res.msg);
                        }
                    })
                    .catch((error) => {
                        console.log(error);
                    });
            } else {
                let params = {
                    name: this.username,
                    id: this.id,
                    description: this.description,
                    deptId:this.deptId,
                };
                getRoleEdit(params)
                    .then((res) => {
                        if (res.code == 200) {
                            this.success();
                        } else {
                            this.$Message.warning(res.msg);
                        }
                    })
                    .catch((error) => {
                        console.log(error);
                    });
            }
        },
        success() {
            this.$Message.success("操作成功");
            this.pageNum = 1;
            this.getList(1);
            this.Editmodal = false;
        },
        cancel(type) {
            if (type === 1) {
                this.Editmodal = false;
            } else if (type === 2) {
                this.deleteModal = false;
            } else if (type == 3) {
                this.treeid = "";
            }
        },
        //后台权限
        getHTRule() {
            let params = {
                platform: 1,
            };
            getRuleModuleList(params)
                .then((res) => {
                    if (res.code == 200) {
                        this.ruleHTlist = res.data.list;
                        for (let i of this.ruleHTlist) {
                            i.title = i.ruleName;
                            i.checked = "";
                            delete i.ruleName;
                        }
                        let arr = ruleTree(res.data.list);
                        for (let i = 0; i < arr.length; i++) {
                            if ( arr[i].type == 1 && arr[i].children && arr[i].children.length > 0 ) {
                                arr[i].children = bubbleSort(arr[i].children);
                                for ( let j = 0; j < arr[i].children.length; j++ ) {
                                    if ( arr[i].children[j].children && arr[i].children[j].children.length > 0 ) {
                                        arr[i].children[j].children = bubbleSort(arr[i].children[j].children);
                                    }
                                }
                            }
                        }
                        this.treeData = bubbleSort(arr);
                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch((error) => {
                    console.log(error);
                });
        },
        //APP权限
        getXCXRule() {
            let params = {
                platform: 2,
            };
            getRuleModuleList(params)
                .then((res) => {
                    if (res.code == 200) {
                        this.ruleXCXlist = res.data.list;
                        for (let i of this.ruleXCXlist) {
                            i.title = i.ruleName;
                            i.checked = "";
                            delete i.ruleName;
                        }
                        let arr = ruleTree(res.data.list);
                        for (let i = 0; i < arr.length; i++) {
                            if ( arr[i].type == 1 && arr[i].children && arr[i].children.length > 0 ) {
                                arr[i].children = bubbleSort(arr[i].children);
                                for ( let j = 0; j < arr[i].children.length; j++ ) {
                                    if ( arr[i].children[j].children && arr[i].children[j].children.length > 0 ) {
                                        arr[i].children[j].children = bubbleSort(arr[i].children[j].children);
                                    }
                                }
                            }
                        }
                        this.treeData1 = bubbleSort(arr);
                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch((error) => {
                    console.log(error);
                });
        },
        removeRow(item) {
            this.deleteModal = true;
            this.ids = item.id;
        },
        detele() {
            getRoleRemove(this.ids)
                .then((res) => {
                    if (res.code == 200) {
                        this.$Message.success("操作成功");
                        this.pageNum = 1;
                        this.current = 1;
                        this.keyword = "";
                        this.getList(2);
                        this.deleteModal = false;
                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch((error) => {
                    console.log(error);
                });
        },
    },
    mounted() {
        this.getHTRule();
        this.getXCXRule();
        this.getDeptList();
        this.btnList = JSON.parse(localStorage.getItem("arr"));
        this.initAuth() //初始化权限
    },
    updated(){

    }
};
</script>
<style lang="less" scoped>
@import "./../../assets/style/themeBase.less";
.main_content {
    width: 100%;
    height: 100%;
    padding: 10px;
    box-sizing: border-box;
    background: #f5f5f5;
    display: flex;
    justify-content: space-between;
    .left {
        width: 300px;
        height: 100%;
        margin-right: 10px;
        background: #fff;
        border-radius: 10px;
        padding: 10px;
        .top {
            display: flex;
            justify-content: flex-start;
            align-items: center;
            width: 280px;
            height: 50px;
        }
        .bottom {
            width: 280px;
            height: calc(100% - 80px);
            overflow-y: hidden;
            margin-top: 20px;
            ul {
                width: 100%;
                display: flex;
                flex-direction: column;
                //   justify-content: center;
                //   align-items: center;
                li {
                    height: 50px;
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    padding: 0 10px;
                    width: 270px;
                    cursor: pointer;
                    border-bottom: 1px solid #f2f2f2;
                    span {
                        width: 200px;
                    }
                    p {
                        width: 50px;
                        display: flex;
                        justify-content: space-between;
                        align-items: center;
                    }
                }
                .active {
                    background: var(--themeColor);
                    color: #fff;
                }
            }
        }
        .bottom:hover{
            overflow-y: auto;
        }
        .bottom::-webkit-scrollbar {
            width: 6px;
        }
        /*滚动槽*/
        .bottom::-webkit-scrollbar-track {
            -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
            box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
            border-radius: 10px;
        }
        /* 滚动条滑块 */
        .bottom::-webkit-scrollbar-thumb {
            border-radius: 10px;
            background: rgba(0, 0, 0, 0.1);
            -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.5);
            box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.5);
        }
        .bottom::-webkit-scrollbar-thumb:window-inactive {
            background: rgba(255, 0, 0, 0.4);
        }
    }
    .right {
        flex: 1;
        height: 100%;
        background: #fff;
        border-radius: 10px;
        padding: 20px;
        /deep/.el-tabs__content {
            height: calc(100% - 100px);
            /deep/.el-tab-pane {
                height: 100%;
            }
        }
        .tree {
            height: calc(100vh - 370px);
            width: 100%;
            overflow-y: scroll;
        }
        .tree::-webkit-scrollbar {
            display: none;
        }
        /*兼容火狐*/
        .tree {
            scrollbar-width: none;
        }
        /* 兼容IE10+ */
        .tree {
            -ms-overflow-style: none;
        }
        .btn {
            width: 100%;
            height: 100px;
            margin-top: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-top: 1px solid #dcdee2;
        }
    }
    /deep/.custom-tree-node{
        width: 100%;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        .title{
            width: 170px;
            font-size: 14px;
            overflow: hidden;
            text-overflow:ellipsis;
            white-space: nowrap;
            margin-left: 10px;
        }
        .sub{
            width: 16px;
            height: 16px;
            background: var(--themeColor);
            color:#fff;
            text-align: center;
            line-height: 20px;
            font-size: 12px;
        }
        .btn{
            margin-right: 10px;
            width: 35px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
    }
}
.tip {
    width:10px !important;
    color: red;
    font-size: 16px;
}
.list {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin-bottom: 10px;

    span {
        width: 70px;
    }
}
</style>
